package com.bestvike.stone.spring.page;

import com.bestvike.stone.spring.exception.BusinessException;
import com.bestvike.stone.spring.exception.ErrorCode;
import com.bestvike.stone.spring.rest.IRequest;
import com.github.pagehelper.PageRowBounds;
import lombok.Data;
import org.apache.ibatis.session.RowBounds;

/**
 * 分页请求
 */
@Data
public class PageableRequest implements IRequest {
    private Integer pageNum;//页码
    private Integer pageSize;//页大小

    /**
     * 验证参数有效性
     */
    public void assertValid() {
        if (this.pageNum == null)
            throw new BusinessException(ErrorCode.ERROR_PARAM, "页码不能为空");
        if (this.pageNum <= 0)
            throw new BusinessException(ErrorCode.ERROR_PARAM, "页码不能为负数或零");
        if (this.pageSize == null)
            throw new BusinessException(ErrorCode.ERROR_PARAM, "页大小不能为空");
        if (this.pageSize <= 0)
            throw new BusinessException(ErrorCode.ERROR_PARAM, "页大小不能为负数或零");
    }

    /**
     * 转换为 RowBounds 类型实例
     */
    public RowBounds toRowBounds() {
        return new PageRowBounds((this.pageNum - 1) * this.pageSize, this.pageSize);
    }
}
